import { LitElement, html, css } from 'lit';
import { customElement, property, state } from 'lit/decorators.js';

/**
 * TabPane标签页面板
 * @element zss-tab-pane
 * @slot default - 标签页内容
 */
@customElement('zss-tab-pane')
export class ZssTabPane extends LitElement {
  static styles = css`
    :host {
      display: none;
    }

    :host([active]) {
      display: block;
    }

    .tab-pane {
      padding: 20px;
    }
  `;

  /**
   * 标签页标题
   * @attr label
   */
  @property({ type: String })
  label = '';

  /**
   * 标签页名称
   * @attr name
   */
  @property({ type: String })
  name = '';

  /**
   * 是否禁用
   * @attr disabled
   */
  @property({ type: Boolean })
  disabled = false;

  /**
   * 是否可关闭
   * @attr closable
   */
  @property({ type: Boolean })
  closable = false;

  /**
   * 是否激活
   * @attr active
   */
  @property({ type: Boolean })
  active = false;

  render() {
    return html`
      <div class="tab-pane">
        <slot></slot>
      </div>
    `;
  }
}

/**
 * Tabs标签页组件
 * @element zss-tabs
 * @slot default - 标签页面板内容
 */
@customElement('zss-tabs')
export class ZssTabs extends LitElement {
  static styles = css`
    .tabs {
      width: 100%;
    }

    .tabs__header {
      border-bottom: 1px solid var(--zss-border-color-light);
      position: relative;
    }

    .tabs__nav {
      display: flex;
      margin: 0;
      padding: 0;
      list-style: none;
      position: relative;
    }

    .tabs__item {
      padding: 0 20px;
      height: 40px;
      line-height: 40px;
      font-size: var(--zss-font-size-base);
      color: var(--zss-text-color-primary);
      cursor: pointer;
      position: relative;
      transition: color 0.3s;
      border: none;
      background: none;
      outline: none;
    }

    .tabs__item:hover {
      color: var(--zss-color-primary);
    }

    .tabs__item--active {
      color: var(--zss-color-primary);
    }

    .tabs__item--active::after {
      content: '';
      position: absolute;
      bottom: -1px;
      left: 0;
      right: 0;
      height: 2px;
      background-color: var(--zss-color-primary);
    }

    .tabs__item--disabled {
      color: var(--zss-text-color-disabled);
      cursor: not-allowed;
    }

    .tabs__item--disabled:hover {
      color: var(--zss-text-color-disabled);
    }

    .tabs__close {
      margin-left: 8px;
      font-size: 12px;
      color: var(--zss-text-color-secondary);
      cursor: pointer;
      padding: 0;
      border: none;
      background: none;
    }

    .tabs__close:hover {
      color: var(--zss-text-color-regular);
    }

    .tabs__content {
      padding: 20px 0;
    }

    /* 卡片样式 */
    .tabs--card .tabs__header {
      border-bottom: none;
    }

    .tabs--card .tabs__nav {
      border: 1px solid var(--zss-border-color-light);
      border-bottom: none;
      border-radius: var(--zss-border-radius-base) var(--zss-border-radius-base) 0 0;
    }

    .tabs--card .tabs__item {
      border-bottom: 1px solid var(--zss-border-color-light);
      border-right: 1px solid var(--zss-border-color-light);
      background: var(--zss-fill-color-light);
    }

    .tabs--card .tabs__item:last-child {
      border-right: none;
    }

    .tabs--card .tabs__item--active {
      background: var(--zss-bg-color);
      border-bottom-color: var(--zss-bg-color);
    }

    .tabs--card .tabs__item--active::after {
      display: none;
    }

    /* 边框卡片样式 */
    .tabs--border-card .tabs__header {
      border-bottom: none;
      background: var(--zss-fill-color-light);
      border: 1px solid var(--zss-border-color-light);
      border-radius: var(--zss-border-radius-base);
    }

    .tabs--border-card .tabs__nav {
      border: none;
    }

    .tabs--border-card .tabs__item {
      border: none;
      border-right: 1px solid var(--zss-border-color-light);
      background: transparent;
    }

    .tabs--border-card .tabs__item:last-child {
      border-right: none;
    }

    .tabs--border-card .tabs__item--active {
      background: var(--zss-bg-color);
      color: var(--zss-color-primary);
    }

    .tabs--border-card .tabs__item--active::after {
      display: none;
    }

    .tabs--border-card .tabs__content {
      padding: 20px;
      border: 1px solid var(--zss-border-color-light);
      border-top: none;
      border-radius: 0 0 var(--zss-border-radius-base) var(--zss-border-radius-base);
    }
  `;

  /**
   * 当前激活的标签页名称
   * @attr value
   */
  @property({ type: String })
  value = '';

  /**
   * 标签页类型
   * @attr type
   */
  @property({ type: String })
  type: 'default' | 'card' | 'border-card' = 'default';

  /**
   * 标签位置
   * @attr tab-position
   */
  @property({ type: String })
  tabPosition: 'top' | 'right' | 'bottom' | 'left' = 'top';

  /**
   * 是否可关闭标签
   * @attr closable
   */
  @property({ type: Boolean })
  closable = false;

  /**
   * 是否在切换标签时销毁内容
   * @attr destroy-on-hide
   */
  @property({ type: Boolean })
  destroyOnHide = false;

  @state()
  private activeName = '';

  @state()
  private panes: ZssTabPane[] = [];

  private slotElement?: HTMLSlotElement;

  connectedCallback() {
    super.connectedCallback();
    this.activeName = this.value || '';
  }

  private handleSlotChange = () => {
    const nodes = this.slotElement?.assignedNodes() || [];
    this.panes = nodes.filter((node): node is ZssTabPane => 
      node instanceof ZssTabPane
    );

    if (this.panes.length > 0 && !this.activeName) {
      const firstEnabledPane = this.panes.find(pane => !pane.disabled);
      if (firstEnabledPane) {
        this.activeName = firstEnabledPane.name || firstEnabledPane.label;
      }
    }

    this.updatePanes();
  };

  private updatePanes() {
    this.panes.forEach(pane => {
      const paneName = pane.name || pane.label;
      pane.active = paneName === this.activeName;
    });
  }

  private handleTabClick(pane: ZssTabPane) {
    if (pane.disabled) return;

    const paneName = pane.name || pane.label;
    if (paneName !== this.activeName) {
      this.activeName = paneName;
      this.updatePanes();
      
      this.dispatchEvent(new CustomEvent('tab-click', {
        detail: {
          name: paneName,
          label: pane.label
        }
      }));

      this.dispatchEvent(new CustomEvent('change', {
        detail: paneName
      }));
    }
  }

  private handleTabClose(pane: ZssTabPane, event: Event) {
    event.stopPropagation();
    
    const paneName = pane.name || pane.label;
    this.dispatchEvent(new CustomEvent('tab-close', {
      detail: {
        name: paneName,
        label: pane.label
      }
    }));
  }

  render() {
    const tabsClasses = [
      'tabs',
      this.type !== 'default' ? `tabs--${this.type}` : '',
      `tabs--${this.tabPosition}`
    ].filter(Boolean).join(' ');

    return html`
      <div class=${tabsClasses}>
        <!-- 标签头 -->
        <div class="tabs__header">
          <nav class="tabs__nav" role="tablist">
            ${this.panes.map(pane => {
              const paneName = pane.name || pane.label;
              const isActive = paneName === this.activeName;
              const isDisabled = pane.disabled;
              const isClosable = pane.closable || this.closable;

              const itemClasses = [
                'tabs__item',
                isActive ? 'tabs__item--active' : '',
                isDisabled ? 'tabs__item--disabled' : ''
              ].filter(Boolean).join(' ');

              return html`
                <button
                  class=${itemClasses}
                  role="tab"
                  aria-selected=${isActive}
                  aria-disabled=${isDisabled}
                  @click=${() => this.handleTabClick(pane)}
                >
                  ${pane.label}
                  ${isClosable ? html`
                    <span 
                      class="tabs__close"
                      @click=${(e: Event) => this.handleTabClose(pane, e)}
                    >
                      ×
                    </span>
                  ` : ''}
                </button>
              `;
            })}
          </nav>
        </div>

        <!-- 标签内容 -->
        <div class="tabs__content">
          <slot @slotchange=${this.handleSlotChange}></slot>
        </div>
      </div>
    `;
  }

  /**
   * 设置当前激活的标签页
   */
  setActiveName(name: string) {
    this.activeName = name;
    this.updatePanes();
  }

  /**
   * 添加标签页
   */
  addPane(pane: ZssTabPane) {
    if (!this.panes.includes(pane)) {
      this.panes.push(pane);
      this.updatePanes();
    }
  }

  /**
   * 移除标签页
   */
  removePane(pane: ZssTabPane) {
    const index = this.panes.indexOf(pane);
    if (index > -1) {
      this.panes.splice(index, 1);
      this.updatePanes();
    }
  }
}

declare global {
  interface HTMLElementTagNameMap {
    'zss-tabs': ZssTabs;
    'zss-tab-pane': ZssTabPane;
  }
}